<?php

/**
 * Theme API
 *
 * @package OWL
 * @subpackage Main
 * @author KeiMOon
 * @since 1.0
 *
 */

define("THEME_SETTING", "setting.xml");
define("THEME_FUNCTIONS", "functions.php");
define("THEME_CUSTOMIZE", "styles/custom.css");

class Owl_Theme_Control {
//Caching is good for your health
    static $current_theme;

    /**
     * Get current theme, what's more?
     *
     * @return string Current theme
     */
    static function get_current_theme() {
        if (!empty(self::$current_theme)) {
            return self::$current_theme;
        }
        else {
            $theme = get_option('current_theme', 'simple');
            if (!file_exists(THEME_PATH . $theme)) {
                if (!file_exists(THEME_PATH . 'simple')) {
                    die ("Your installation is corrupted!");
                }
                else {
                    $theme = 'simple';
                }
            }
            self::$current_theme = $theme;
            return $theme;
        }
    }

    /**
     * Current theme's path
     *
     * @return string The path
     */
    static function get_current_theme_path() {
        return THEME_PATH . self::get_current_theme() . "/";
    }

    /**
     * Load a theme setting, if possible
     *
     * @param string $theme_name
     * @return array
     */
    static function load_setting($theme_name) {
        $path = THEME_PATH . $theme_name . "/" . THEME_SETTING;
        if (!file_exists($path)) {
            return false;
        }
        $theme_setting = new Owl_Theme($theme_name);
        return $theme_setting->get_all_settings();
    }

    static function is_colorirable($theme_name) {
        $theme_setting = self::load_setting($theme_name);
        if ($theme_setting["use_color_scheme"] && is_array($theme_setting["color_schemes"])) {
            return count($theme_setting["color_schemes"]);
        }
        else {
            return false;
        }
    }

    static function is_customizable($theme_name) {
        $theme_setting = self::load_setting($theme_name);
        if ($theme_setting["customizable"] && is_array($theme_setting["customizes"])) {
            $file = THEME_PATH . $theme_name . "/" . THEME_CUSTOMIZE;
            if (file_exists($file) && is_writable($file)) {
                return 1;
            }
            else {
                return -1;
            }
        }
        else {
            return 0;
        }
    }

    static function is_colorizable_message($theme_name) {
        if ($color_schemes = self::is_colorirable($theme_name)) {
            return sprintf(__("This theme has %d color schemes"), $color_schemes);
        }
        else {
            return __("This theme does not have any color schemes");
        }
    }

    static function is_customizable_message($theme_name) {
        if (self::is_customizable($theme_name) == 1) {
            return __("This theme support customization");
        }
        elseif (self::is_customizable($theme_name) == 0) {
            return __("This theme does not support customization");
        }
        elseif (self::is_customizable($theme_name) == -1) {
            return sprintf(__("This theme support customization, but the <code>%s</code> 

                               file is not writable or not found"), THEME_CUSTOMIZE);
        }
    }

    static function print_theme_info($theme_name) {
        $theme_setting = self::load_setting($theme_name);
        $theme_info = array(
            "<b>" . __("Theme's name") . "</b>: " . $theme_setting["theme_name"],
            "<b>" . __("Theme's author") . "</b>: " . $theme_setting["theme_author"],
            "<b>" . __("Theme's version") . "</b>: " . $theme_setting["theme_version"],
            "<b>" . __("Theme's description") . "</b>: " . $theme_setting["theme_description"],
            "<b>" . __("Color schemes") . "</b>: " . Owl_Theme_Control::is_colorizable_message($theme_name),
            "<b>" . __("Color customization") . "</b>: " . Owl_Theme_Control::is_customizable_message($theme_name)
        );
        echo Owl_Html::make_it_list($theme_info);
    }

    static function get_theme_preview_url($theme_setting, $theme_name) {
        return Owl_Link::theme_url(false) . $theme_name ."/" . $theme_setting["theme_preview"];
    }

    static function get_color_scheme_preview_url($color_scheme_setting, $theme_name) {
        return Owl_Link::theme_url(false) . $theme_name ."/" . $color_scheme_setting["scheme_preview"];
    }

    static function get_customization($theme_name) {
        $theme_setting = self::load_setting($theme_name);
        $customizes = $theme_setting["customizes"];
        $css_parser = new cssparser();
        $css_parser->Parse(THEME_PATH . $theme_name . "/" . THEME_CUSTOMIZE);
        foreach ($customizes as $key => $customize) {
            $value = $css_parser->Get($customize["selector"], $customize["property"]);
            $customizes[$key]["value"] = $value;            
        }
        return $customizes;
    }

    static function encode_customize_name($customization) {
        $string = $customization["selector"] . "/" . $customization["property"];
        $search = array(" ", ".");
        $replace = array("_", "|");
        return str_replace($search, $replace, $string);
    }

    static function decode_customize_name($encoded_name) {
        $name_array = explode("/", $encoded_name);
        $replace = array(" ", ".");
        $search = array("_", "|");
        $selector = str_replace($search, $replace, $name_array[0]);
        $property = str_replace($search, $replace, $name_array[1]);
        return array($selector, $property);
    }

    /**
     * Load setting of all themes
     *
     * @return array
     */
    static function load_all_setting() {
        $handle = @opendir(THEME_PATH);
        if ($handle === false) {
            die("Cannot find default theme directory!!!");
        }
        $all_settings = array();
        while (false !== ($file = readdir($handle))) {
            if (Owl_Functions::is_legitimate_dir(THEME_PATH . $file)) {
                if ($setting = self::load_setting($file)) {
                    $all_settings[$file] = $setting;
                }
            }
        }
        closedir($handle);
        return $all_settings;
    }

    /**
     * Print the class of body element, pls use this if your theme uses color
     * schemes, customization or you want to fight againts MSIE
     */
    static function print_body_class() {
        $color_scheme_class =  get_option('current_body_class');
        Owl_Functions::print_css_namespace($color_scheme_class);
    }

    /**
     * Load theme function file, if possible, do not use this function, it has
     * been already called before.
     */
    static function load_theme_functions() {
        $path = self::get_current_theme_path() . THEME_FUNCTIONS;
        if (file_exists($path)) {
            include_once $path;
        }
    }

    static function change_color_scheme($color_scheme) {
        return update_option('current_body_class', $color_scheme);
    }

    static function customize_theme($customize_data) {
        $filename = THEME_PATH . self::get_current_theme() . "/" . THEME_CUSTOMIZE;
        if (!is_writable($filename)) {
            return false;
        }

        $content = "";

        foreach ($customize_data as $customize => $value) {
            list($selector, $property) = self::decode_customize_name($customize);
            $content .= $selector ." { \n\t" . $property . ":" . $value. "; \n} \n";
        }
        if (Owl_Functions::safe_write_file($filename, $content)) {
            return true;
        }
        else {
            return false;
        }
    }

    static function set_default_customization() {
        $theme_setting = self::load_setting(self::get_current_theme());
        $customize_data = $theme_setting["customizes"];
        $filename = THEME_PATH . self::get_current_theme() . "/" . THEME_CUSTOMIZE;
        if (!is_writable($filename)) {
            return false;
        }

        $content = "";

        foreach ($customize_data as $customize) {
            $content .= $customize["selector"] ." { \n\t" . $customize["property"] . ":" . $customize["default"] . "; \n} \n";
        }
        if (Owl_Functions::safe_write_file($filename, $content)) {
            return true;
        }
        else {
            return false;
        }
    }

    static function change_theme($theme_name) {
        $theme_setting = self::load_setting($theme_name);
        if ($theme_setting == false) {
            return false;
        }

        if (self::is_colorirable($theme_name)) {
            $new_body_class = $theme_setting["color_schemes"][0]["scheme_class"];
        }
        else {
            $new_body_class = "no-class";
        }

        return (update_option("current_theme", $theme_name) && update_option("current_body_class", $new_body_class));
    }

 }